package com.ruoyi.cms.interceptor;

import com.ruoyi.cms.domain.SysSite;
import com.ruoyi.cms.service.ISysSiteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class SiteInterceptor implements HandlerInterceptor {
    
    private static Logger log = LoggerFactory.getLogger(SiteInterceptor.class);
    @Autowired
    private ISysSiteService sysSiteService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 访问域名
        String serverName = request.getServerName();
        // 访问端口号
        int port = request.getServerPort();
        String url = "//%s%s";
        String portStr = "";
        if (port != 80) {
            portStr += ":" + port;
        }
        String sitePath = String.format(url, serverName, portStr);
        log.info(sitePath);
        SysSite sysSite = sysSiteService.selectBySitePath(sitePath);
        if (sysSite == null) {
            response.setCharacterEncoding("UTF-8");//设置将字符以"UTF-8"编码输出到客户端浏览器
            PrintWriter out = response.getWriter();//获取PrintWriter输出流
            response.setHeader("content-type", "text/html;charset=UTF-8");
            out.write(sitePath +" 还未开通站点");
            return false;
        } else {
            request.getSession().setAttribute("site", sysSite);
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        
    }

}